# -*-coding:utf-8 -*-
import main.ble_scan
import main.ty_log
from bluepy.btle import Scanner
import time
import threading
import prettytable as pt
import json


# 全局变量 wifi 蓝牙 输出信打印到dic
dic = {}

#  低功耗蓝牙
def bleScan():
    global dic

    while True:
        print '-----------------------低功耗蓝牙----------------------'
        scanner = Scanner().withDelegate(main.ble_scan.ScanDelegate())
        devices = scanner.scan()
        tb = pt.PrettyTable()
        tb.field_names = ["MAC", "MAC类型", "信号强度", "Flags", "厂商", "服务(UUID)", "属性", "handle", "ch_type", "detail"]
        for dev in devices:

            print '**************************************************************************'
            print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
            print dev.getScanData()
            for (adtype, desc, value) in dev.getScanData():
                print "  %s = %s" % (desc, value)
                if desc == 'Manufacturer':
                    manufac = value
            services = ''
            if manufac[0:8] == '4c001005':
                continue
            else:
                info = main.ble_scan.Ble(dev.addr, dev.addrType).getInfo()
                # print '1111',info
                # if info == 1 or info == 2:
                #   print 'the host is down...'
                for k, v in info.items():
                    # print '*************************************************************************************************'
                    # print '>>>>', k.split('<')[1].split('>')[0]
                    if v:
                        for ch, detail in v.items():
                            # print '>>>>>>>>>>>', ch
                            # print detail.split('<')
                            tb.add_row([dev.addr, dev.addrType, dev.rssi, dev.getScanData()[0][2], manufac,
                                        k.split('<')[1].split('>')[0], ch.split('<')[1].split('>')[0], detail[0],
                                        detail[1], detail])
            print tb
        dic['LOW POWER BLUETOOTH'] = info
       # sleep(10)

# 创建线程
threads = []

# 低功耗蓝牙
ble = threading.Thread(target=bleScan)
threads.append(ble)
if __name__ == '__main__':

    for t in threads:
        t.setDaemon(True)
        t.start()
    # ble.start()
    while True:
        time.sleep(5)
        print 'Print -----------dic----------------------------------'
        main.ty_log.info(dic)
        main.ty_log.send_to_syslog(json.dumps(dic))
        print dic